﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;
using 收入分析.Model;
using 收入分析.Services;

namespace 收入分析.ViewModel;

internal partial class LoadViewModel : ObservableObject {
    #region 属性
    [ObservableProperty]
    private string? importFileName;
    [ObservableProperty]
    private List<FieldList> fieldsList;
    [ObservableProperty]
    private List<DataBaseType> dBTypeList;
    [ObservableProperty]
    private DataBaseType dBTypeSelect;
    [ObservableProperty]
    private DateTime dBYearSelect = DateTime.Now;
    [ObservableProperty]
    private int dataStartLine = 3;
    [ObservableProperty]
    private string[] excelTemplateList;//= SystemManager.Config?.ExcelTemplate?.Select(x => x.Name).ToArray();
    [ObservableProperty]
    private string? selectedTemplate;

    public LoadViewModel() {
        DBTypeList = Enum.GetValues(typeof(DataBaseType)).Cast<DataBaseType>().ToList();
    }


    #endregion
    #region 命令
    [RelayCommand]
    private async Task Loaded() {
        //var list = SystemManager.GetDataBaseList();
    }
    [RelayCommand]
    private void DbTypeSelected() {
        Debug.WriteLine($"{DBTypeSelect} @ {DBYearSelect}");
        switch (DBTypeSelect) {
            case DataBaseType.全字段:
                break;
            case DataBaseType.系统收入2002:
                DBYearSelect = DateTime.Parse("2022/12/31");
                break;
            case DataBaseType.采集收入:
                break;
            case DataBaseType.搬迁户信息:
                break;
            default:
                break;
        }
    }
    /// <summary>
    /// 异步导入数据库
    /// </summary>
    [RelayCommand]
    private async Task ImportDataAsync() {
        if (string.IsNullOrEmpty(ImportFileName)) {
            Growl.Error("请选择需要导入的文件");
            return;
        }
        var tables = SystemManager.GM.DataBaseList;
        var table = new DataTableInfo(DBTypeSelect, DBYearSelect);
        if (tables.Contains(table.Name)) {
            table.Name = $"{DBTypeSelect}_{DBYearSelect:yyyy_MMdd_HHmmssff}";
        }
        switch (DBTypeSelect) {
            case DataBaseType.全字段:
                var j = await ImportSystemAllDataAsync(ImportFileName, table);
                if (j > 0) Growl.Info($"共插入 {j} 数据");
                else {
                    Growl.Error("导入数据出错");
                    return;
                }
                break;
            case DataBaseType.系统收入2002:
                await ImportSystemIncome2022Async(table);
                break;
            case DataBaseType.采集收入:
            case DataBaseType.搬迁户信息:
                break;
            default:
                break;
        }
        _ = await SystemManager.GM.AddTableInfomationAsync(table);
    }
    /// <summary>
    /// 导入 2022系统收入库
    /// </summary>
    private async Task<int> ImportSystemIncome2022Async(DataTableInfo table) {
        if (string.IsNullOrEmpty(ImportFileName)) {
            SystemManager.PostStatusBarMessage("请选择需要导入的文件");
            return 0;
        }
        string[] _fields = SystemManager.GM.Config?.ExcelTemplate?.Where(x => x.Name == "系统收入2022年").Select(x => x.Fields).First()
            ?? new string[]{"市州","县市区","乡镇","行政村","户号","户主姓名","户主证件号码","家庭人口数",
                "总收入","人均纯收入","纯收入",
                "工资性收入","生产经营性收入","生产经营性支出","计划生育金","低保金","特困供养金","养老保险金","生态补偿金","其他转移性收入","资产收益扶贫分红收入","其他财产性收入",};

        if (!await IncomeBase<收入信息2022>.CleanTableAsync(table.Name)) {
            Growl.Error("清空原数据出错"); return 0;
        }
        List<收入信息2022> datalist = new();
        using var reader = MiniExcel.GetReader(ImportFileName, startCell: "A2");
        while (reader.Read()) {
            收入信息2022 _data = new();
            for (int i = 0; i < reader.FieldCount; i++) {
                var value = reader.GetValue(i);
                _data.SetValue(_fields[i], value);
            }
            datalist.Add(_data);
        }
        table.ColumnNum = reader.FieldCount + 1;
        table.RowNum = await IncomeBase<收入信息2022>.BulkCopy(table.Name, datalist);
        Growl.Info($"共增加 {table.RowNum} 条记录");
        return table.RowNum;
    }
    /// <summary>
    /// 导入 2023年收入采集库
    /// </summary>
    [RelayCommand]
    private void ImportGather2023() {
        if (string.IsNullOrEmpty(ImportFileName)) {
            SystemManager.PostStatusBarMessage("请选择需要导入的文件");
            return;
        }
    }
    /// <summary>
    /// 导入 2022年收入采集库
    /// </summary>
    [RelayCommand]
    private void ImportGather2022() {
        if (string.IsNullOrEmpty(ImportFileName)) {
            SystemManager.PostStatusBarMessage("请选择需要导入的文件");
            return;
        }
    }
    /// <summary>
    /// 导入 其他库
    /// </summary>
    [RelayCommand]
    private void ImportOtherDb() {
        if (string.IsNullOrEmpty(ImportFileName)) {
            SystemManager.PostStatusBarMessage("请选择需要导入的文件");
            return;
        }
        if (SelectedTemplate is null) return;

        if ("全字段".Equals(SelectedTemplate) ||
           SystemManager.GM.Config?.ExcelTemplate?.Where(x => x.Name == SelectedTemplate).Select(x => x.Fields).First() is null) {
            Debug.WriteLine("使用默认全字段导入");
        }
        else {

        }
    }
    [RelayCommand]
    private void OpenFileButtonClick() {
        //创建一个打开文件的对话框
        Microsoft.Win32.OpenFileDialog dialog = new() {
            Filter = "Excel Files|*.xlsx",
            //InitialDirectory = @"C:\Users\62584\Desktop",
        };
        //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
        if (dialog.ShowDialog().GetValueOrDefault()) {
            ImportFileName = dialog.FileName;
        }
        else {
            ImportFileName = string.Empty;

            Growl.Info("操作取消");
            return;
        }
        return;
    }

    /// <summary>
    /// 计算近2年收入增幅情况
    /// </summary>
    [RelayCommand]
    private void RateIncome() {

    }
    #endregion
    #region 私有字段和函数
    private async Task<List<全字段>> PropertiesToDataListAsync(string path) {
        var title = MiniExcel.Query(path, startCell: "A3").Cast<IDictionary<string, object>>().First();
        var titleColl = title.ToDictionary(k => Util.ReplaceChar(k.Value), p => p.Key);
        List<全字段> datalist = new();
        var excelData = await MiniExcel.QueryAsync(path, startCell: "A4");
        if (excelData == null) {
            return datalist;
        }
        foreach (IDictionary<string, object> row in excelData) {
            全字段 _data = new();
            var prop = typeof(全字段).GetProperties();
            for (var i = 0; i < prop.Length; i++) {
                var name = Util.ReplaceChar(prop[i].Name);
                if (titleColl.ContainsKey(name) && row.ContainsKey(titleColl[name])) {
                    var value = row[titleColl[name]];
                    try {
                        if (!prop[i].PropertyType.IsGenericType) {
                            //非泛型
                            prop[i].SetValue(_data, value == null ? null
                            : string.IsNullOrWhiteSpace(value.ToString()) ? null
                            : Convert.ChangeType(value, prop[i].PropertyType), null);
                        }
                        else {
                            //泛型Nullable<>
                            Type genericTypeDefinition = prop[i].PropertyType.GetGenericTypeDefinition();
                            if (genericTypeDefinition == typeof(Nullable<>)) {
                                prop[i].SetValue(_data, value == null ? null
                                : string.IsNullOrWhiteSpace(value.ToString()) ? null
                                : Convert.ChangeType(value, Nullable.GetUnderlyingType(prop[i].PropertyType)), null);
                            }
                        }
                    }
                    catch (Exception ex) {
                        Debug.Write($"Exception {ex.Message}:");
                        Debug.WriteLine($"{name} {value}");
                        continue;
                    }
                }
            }
            datalist.Add(_data);
        }
        return datalist;
    }
    private async Task<int> ImportSystemAllDataAsync(string path, DataTableInfo table) {
        List<全字段> list = await PropertiesToDataListAsync(path);
        if (list == null) {
            Growl.Error("数据读取失败");
            return -1;
        }
        if (list.Count == 0) {
            Growl.Error("未读取到无数据");
            return 0;
        }
        table.ColumnNum = 187;
        Debug.WriteLine("数据生成完毕，准备插入数据库");
        if (!await FullDataManager.CleanTable(table.Name)) {
            Growl.Error("清空原数据失败");
            return -2;
        }
        table.RowNum = await FullDataManager.BulkCopy(table.Name, list);
        return table.RowNum;
    }
    /// <summary>
    /// 对比测试函数：已弃用
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    //private async Task<List<全字段>> ExcelFileToDataListAsync(string path)
    //{
    //    var excelData = await MiniExcel.QueryAsync(path, startCell: "A4");
    //    if (excelData == null)
    //    {
    //        return null;
    //    }
    //    var savePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.xlsx");
    //    MiniExcel.SaveAs(savePath, excelData);
    //    var rows = MiniExcel.Query<全字段>(savePath).ToList();
    //    File.Delete(savePath);
    //    return rows;
    //}
    #endregion
}
